<template>
  <div>
    <div class="box-header mt-5">
      <h2>
        <i class="el-icon-document title-logo" />
        {{ $t('modules.tms.terminal.device_event') }}
      </h2>
      <hr class="mb-3" />
    </div>
    <el-card
      :body-style="{ padding: '0px' }"
      shadow="never"
      @current-change="currentChangeHandle"
      :page-size.sync="pageSize"
      :total="totalPage"
      :current-page="pageIndex"
      @page-size-change="
        (size) => {
          pageSize = size
          fetchData()
        }
      "
    >
      <div class="search-box">
        <el-form @submit.prevent.native inline :model="dataForm">
          <el-form-item>
            <el-select
              clearable
              v-model="dataForm.userId"
              :placeholder="$t('system.log.operator_name')"
              size="small"
              style="width: 230px"
            >
              <el-option
                v-for="item in userPage"
                :key="item.userId"
                :label="item.name"
                :value="item.userId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input
              v-model="dataForm.snOrTid"
              maxlength="50"
              :placeholder="$t('modules.tms.terminal.device_sn_tid')"
              size="small"
              style="width: 200px"
              @blur="() => (dataForm.snOrTid = dataForm.snOrTid.trim())"
              @keyup.enter.native="fetchData((pageNo = 1))"
            />
          </el-form-item>
          <el-form-item>
            <el-input
              v-model="dataForm.mrchNameOrMid"
              maxlength="256"
              :placeholder="$t('modules.tms.terminal.merchant_name_mid')"
              size="small"
              style="width: 200px"
              @blur="
                () => (dataForm.mrchNameOrMid = dataForm.mrchNameOrMid.trim())
              "
              @keyup.enter.native="fetchData((pageNo = 1))"
            />
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="dataForm.eventType"
              clearable
              :placeholder="$t('modules.tms.terminal.event_type_field')"
              size="small"
              style="width: 180px"
            >
              <el-option
                v-for="item in eventTypeList"
                :key="item.key"
                :label="item.value"
                :value="item.key"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="dataForm.eventStatus"
              clearable
              :placeholder="$t('modules.tms.terminal.event_status_field')"
              size="small"
              style="width: 180px"
            >
              <el-option
                v-for="item in eventStatusList"
                :key="item.key"
                :label="item.value"
                :value="item.key"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-date-picker
              v-model="dataForm.eventTime"
              type="daterange"
              value-format="x"
              :start-placeholder="$t('modules.tms.terminal.event_time_field')"
              :end-placeholder="$t('modules.tms.terminal.event_time_field')"
              size="small"
              style="width: 230px"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              class="align-middle p-1.5"
              size="small"
              @click="fetchData((pageIndex = 1))"
            >
              <svg-icon icon-class="search" class="text-lg" />
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              class="align-middle p-2"
              @click="exportData"
            >
              <i class="el-icon-download" />
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table v-loading="listLoading" :data="tableData" stripe>
        <el-table-column label="SN" prop="devSn" width="200px">
        </el-table-column>
        <el-table-column label="TID" prop="devTid" width="200px" />
        <el-table-column
          :label="$t('modules.tms.terminal.event_type_field')"
          prop="eventType"
          width="250px"
        >
          <template v-slot="scope">
            <div>
              <span>{{
                $t('modules.tms.terminal.event_type_tip.' + scope.row.eventType)
              }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('modules.tms.terminal.event_status_field')"
          prop="eventStatus"
          width="150px"
        >
          <template v-slot="scope">
            <el-tooltip
              :disabled="scope.row.eventStatus === 1"
              style="cursor: pointer"
              :content="getErrMsgInfo(scope.row.description)"
            >
              <div>
                <span>{{
                  $t(
                    'modules.tms.terminal.event_status_tip.' +
                      scope.row.eventStatus
                  )
                }}</span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('modules.tms.terminal.event_description_field')"
          prop="description"
        >
          <template v-slot="scope">
            <div>
              <span>{{ show(scope.row) }}</span>
            </div>
            <!--                  <i @click="handleDetails(scope.row)" class="el-icon-info" style="cursor: pointer;" ></i>-->
            <!--            <el-tooltip v-if='scope.row.eventStatus === 0' class="el-icon-info" style="cursor: pointer;" :content="getErrMsgInfo(scope.row.description) ">-->
            <!--              <button class="p-2">-->
            <!--                <svg-icon icon-class="el-icon-info" />-->
            <!--              </button>-->
            <!--            </el-tooltip>-->
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('system.log.operator_name')"
          prop="operator"
          width="200px"
        />
        <el-table-column
          :label="$t('modules.tms.terminal.event_time_field')"
          prop="eventTime"
          width="160px"
        >
          <template v-slot="{ row }">
            <div>
              <span>{{ dateTimeFilter(row.eventTime) }}</span>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { getErrMsgInfo, parseTime } from '@/utils/index'
import { dateTimeFilter } from '@/filters'
import { getToken, hasPermission } from '@/utils/auth'
import { formatDate } from '@/utils/formatDate'
import { getDeviceEvent } from '@/api/terminal'
import axios from 'axios'
import store from '@/store'
import { getAllUser } from '@/api/user'

export default {
  components: {},
  data() {
    return {
      tableData: [],
      listLoading: false,
      status: '',
      snOrTid: '',
      pageIndex: 1,
      totalPage: 0,
      pageSize: 10,
      userPage: [],
      dataForm: {
        userId: null,
        snOrTid: '',
        mrchNameOrMid: '',
        eventStatus: '',
        eventType: '',
        eventTime: []
      },
      selectedMerchant: '',
      batchOperation: [],
      oneOperation: [{ action: 'view', class: 'toolbar-delete' }],
      selectedData: [],
      mrchNameOrMid: '',
      queryOrg: {},
      orgId: ''
    }
  },
  computed: {
    eventTypeList() {
      var eventTypeObj = this.$t('modules.tms.terminal.event_type_tip')
      var eventTypeList = []

      for (let key in eventTypeObj) {
        var item = { key: key, value: eventTypeObj[key] }
        console.log(key) //a b c d
        console.log(eventTypeObj[key]) // aa bb cc dd
        eventTypeList.push(item)
        console.log(JSON.stringify(eventTypeList))
      }
      return eventTypeList
    },
    eventStatusList() {
      var eventTypeObj = this.$t('modules.tms.terminal.event_status_tip')
      var eventTypeList = []

      for (let key in eventTypeObj) {
        var item = { key: key, value: eventTypeObj[key] }
        console.log(key) //a b c d
        console.log(eventTypeObj[key]) // aa bb cc dd
        eventTypeList.push(item)
        console.log(JSON.stringify(eventTypeList))
      }
      return eventTypeList
    }
  },
  mounted() {
    this.initDate()
    this.fetchData()
    this.getAllUser()
  },
  methods: {
    dateTimeFilter,
    statusFilter(status) {
      const statusMap = {
        0: 'offline',
        1: 'online'
      }
      return statusMap[status]
    },
    hasPermission,
    currentChangeHandle(val) {
      this.pageIndex = val
      this.fetchData()
    },
    sizeChangeHandle(val) {
      this.pageSize = val
      this.fetchData()
    },
    initDate() {
      const now = new Date().getTime()
      const endTime = now
      const startTime = now - 7 * 24 * 3600 * 1000
      this.$set(this.dataForm.eventTime, 0, startTime)
      this.$set(this.dataForm.eventTime, 1, endTime)
      // this.$set(this.dataForm, 'beginTime', parseTime(startTime))
      // this.$set(this.dataForm, 'endTime', parseTime(endTime))
    },
    getErrMsgInfo(msg) {
      return getErrMsgInfo(msg)
    },
    async exportData() {
      var beginTime, endTime
      if (this.dataForm.eventTime && this.dataForm.eventTime.length === 2) {
        beginTime = parseInt(this.dataForm.eventTime[0] / 1000)
        endTime = parseInt(this.dataForm.eventTime[1] / 1000 + 60 * 60 * 24)
      } else {
        this.$message.error(this.$t('modules.vas.geo.time_not_null'))
        return
      }
      let path =
        process.env.VUE_APP_BASE_API +
        '/online/management/operator/device/event/export?WEB-TOKEN=' +
        getToken() +
        '&timezone=' +
        this.$store.state.app.timezone
      if (beginTime) {
        path += '&beginTime=' + beginTime
      }
      if (endTime) {
        path += '&endTime=' + endTime
      }
      if (this.dataForm.eventStatus) {
        path += '&eventStatus=' + this.dataForm.eventStatus
      }
      if (this.dataForm.snOrTid) {
        path += '&snOrTid=' + this.dataForm.snOrTid
      }
      if (this.dataForm.eventType) {
        path += '&eventType=' + this.dataForm.eventType
      }
      if (this.dataForm.mrchNameOrMid) {
        path += '&mrchNameOrMid=' + this.dataForm.mrchNameOrMid
      }
      if (this.dataForm.userId !== null) {
        path += '&userId=' + this.dataForm.userId
      }
      const res = await fetch(path)
      const blob = await res.blob()
      // console.log(blob.size)
      if (blob.size === 0) {
        this.$store.dispatch('app/fetchTaskData')
      } else {
        window.location.href = path
      }
    },
    fetchData() {
      var beginTime, endTime
      if (this.dataForm.eventTime && this.dataForm.eventTime.length === 2) {
        beginTime = parseInt(this.dataForm.eventTime[0] / 1000)
        endTime = parseInt(this.dataForm.eventTime[1] / 1000 + 60 * 60 * 24)
      } else {
        this.$message.error(this.$t('modules.vas.geo.time_not_null'))
        return
      }

      this.listLoading = true
      console.log(this.dataForm.beginTime)
      getDeviceEvent({
        pageNo: this.pageIndex,
        pageSize: this.pageSize,
        beginTime: beginTime,
        endTime: endTime,
        eventStatus: this.dataForm.eventStatus,
        snOrTid: this.dataForm.snOrTid,
        mrchNameOrMid: this.dataForm.mrchNameOrMid,
        userId: this.dataForm.userId,
        eventType: this.dataForm.eventType
      }).then((res) => {
        this.listLoading = false
        this.tableData = res.data
        this.totalPage = res.rows
        this.listLoading = false
      })
    },
    getAllUser() {
      getAllUser({ condition: '', platCode: 'PASS' })
        .then((res) => {
          this.listLoading = false
          this.userPage = res
          // this.userPage添加tomsclint操作员
          this.userPage.unshift({ userId: -1, name: 'TOMSCLIENT' })
          console.log(this.userPage)
        })
        .catch((e) => {
          this.listLoading = false
          this.$confirmError(e)
        })
    },
    goBack() {
      window.history.go(-1)
    },
    format(time, format) {
      var timeFormat = formatDate(
        new Date(time).getTime() / 1000,
        'yyyy-MM-dd hh:mm:ss',
        0
      )
      return timeFormat
    },
    back() {
      this.$router.back(-1)
    },
    show(row) {
      if (
        row.eventType === 1 ||
        row.eventType === 21 ||
        row.eventType === 22 ||
        row.eventType === 23 ||
        row.eventType === 24 ||
        row.eventType === 25
      ) {
        return row.target1
      } else {
        return row.target2 !== null
          ? row.target2
          : row.target1 + row.target3 !== null
            ? '|' + row.target3
            : ''
      }
    },
    downLoad(url, params) {
      this.exportLoading = true
      axios({
        method: 'get',
        url: url,
        responseType: 'blob',
        headers: {
          'WEB-TOKEN': getToken(),
          LANG:
            localStorage.getItem(store.state.user.keys.storage.lang) || 'en-US',
          'time-zone': this.$store.state.app.timezone
        },
        params: params
      })
        .then((res) => {
          const data = res.data
          if (data) {
            const dis = res.headers['content-disposition']
            if (dis) {
              const fileName = dis.split('attachment;filename=')[1]
              const url = window.URL.createObjectURL(data)
              const a = document.createElement('a')
              a.href = url
              a.download = fileName
              a.click()
            } else {
              // this.$message.success('Export processing')
              // this.$store.commit('app/OPEN_TASK_PROGRESS')
              this.$message.success(this.$t('common.export_processing'))
              this.$store.dispatch('app/fetchTaskData')
            }
          } else {
            this.$message.error(this.$t('common.export_error'))
          }
        })
        .catch((e) => {
          this.$confirmError(e)
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.pagination-wrapper {
  text-align: right;
}

.circle {
  display: inline-block;
  margin-right: 10px;
  border-radius: 50%;
  width: 6px;
  height: 6px;

  &.active {
    background-color: #52c41a;
  }

  &.inactive {
    background-color: #ff8d1a;
  }

  &.disable {
    background-color: #a6a6a6;
  }
}

.device-online {
  color: #059669;
}

.device-offline {
  color: #d97706;
}
</style>
